<template>
  <List>
    <Row :gutter="24" :style="{ paddingLeft: '20px' }">
      <Col :span="rad" :style="{ display: 'flex', justifyContent: 'center' }">
      <List.Item :style="{
        display: 'inline-block',
        paddingLeft: '1px',
        paddingRight: '1px',
      }">
        <Button type="primary" @click="btnAddLink">添加链接</Button>
      </List.Item>
      </Col>
      <Col :span="rad" :style="{ display: 'flex', justifyContent: 'center' }">
      <List.Item :style="{
        display: 'inline-block',
        paddingLeft: '1px',
        paddingRight: '1px',
      }">
        <Button type="primary" @click="btnAddLinkType">添加类别</Button>
      </List.Item>
      </Col>
      <Col :span="rad" :style="{ display: 'flex', justifyContent: 'center' }">
      <List.Item :style="{
        display: 'inline-block',
        paddingLeft: '1px',
        paddingRight: '1px',
      }">
        <Button @click="selOften">常用链接</Button>
      </List.Item>
      </Col>
      <template v-for="item in linktypedata" :key="item.name">
        <Col :span="rad" :style="{ display: 'flex', justifyContent: 'center' }">
        <Dropdown :trigger="['contextmenu']">
          <List.Item :style="{
            display: 'inline-block',
            paddingLeft: '1px',
            paddingRight: '1px',
          }">
            <Button @click="selLinkByType(item)" class="ml-1">
              {{ item.name }}
            </Button>
          </List.Item>
          <template #overlay>
            <Menu>
              <MenuItem key="1" @click="clickLinkType(item)">修改</MenuItem>
              <Popconfirm title="确定删除?" ok-text="确定" cancel-text="取消" @confirm="delLinkType(item)">
                <MenuItem key="2">删除</MenuItem>
              </Popconfirm>
            </Menu>
          </template>
        </Dropdown>
        </Col>
      </template>
    </Row>
  </List>

  <div :class="`${prefixCls}__content`">
    <List :style="{ paddingLeft: '20px' }">
      <Row :gutter="24">
        <template v-for="item in linkdata" :key="item.name">
          <Col :span="radl" :style="{ paddingLeft: '1px', paddingRight: '1px' }">
          <Dropdown :trigger="['contextmenu']">
            <List.Item :style="{ paddingLeft: '2px', paddingRight: '2px' }">
              <Card @click="jumpWebUrl(item)" :hoverable="true" :class="`${prefixCls}__card`"
                :bodyStyle="{ padding: '15px 5px 5px 15px' }">
                <!-- <div class="child-div">{{ item.num }}</div> -->
                <div :class="`${prefixCls}__card-title`">
                  <Image v-if="item.icon" :src="item.icon" :width="26" :preview="false"></Image>
                  <TypographyParagraph :ellipsis="{ rows: 1 }" :style="{
                    marginBottom: '0px',
                    padding: '0px 0px 0px 10px',
                  }" :content="item.name">
                  </TypographyParagraph>
                </div>
                <div :class="`${prefixCls}__card-detail`">
                  <Tooltip :title="item.urlname" color="blue">
                    <TypographyParagraph :ellipsis="{ rows: 1 }" :style="{ marginBottom: '0px' }"
                      :content="item.urlname">
                    </TypographyParagraph>
                  </Tooltip>
                </div>
              </Card>
            </List.Item>
            <template #overlay>
              <Menu>
                <MenuItem key="1" @click="clickLink(item)">修改</MenuItem>
                <Popconfirm title="确定删除?" ok-text="确定" cancel-text="取消" @confirm="delLinks(item)">
                  <MenuItem key="2">删除</MenuItem>
                </Popconfirm>
              </Menu>
            </template>
          </Dropdown>
          </Col>
        </template>
      </Row>
    </List>
  </div>
  <Modal @ok="submitLinkType(true)" @cancel="submitLinkType(false)" :title="linkTypeTitle" v-model:open="opentype">
    <Form>
      <FormItem label="链接类型名称">
        <Input v-model:value="paramsType.name" />
      </FormItem>
    </Form>
  </Modal>
  <Modal @ok="submitLink(true)" @cancel="submitLink(false)" :title="linkTitle" v-model:open="open">
    <Form>
      <FormItem label="链接地址">
        <InputSearch v-model:value="params.urlpath" placeholder="" size="middle" @search="onSearch">
          <template #enterButton>
            <Button class="bg-white">获取</Button>
          </template>
        </InputSearch>
      </FormItem>
      <FormItem label="连接名称">
        <Input v-model:value="params.name" />
      </FormItem>
      <FormItem label="地址描述">
        <Input v-model:value="params.urlname" />
      </FormItem>
      <FormItem label="链接类型">
        <Select ref="select" v-model:value="params.type" :options="optionsType" />
      </FormItem>
      <FormItem label="链接图片">
        <Upload list-type="picture-card" :multiple="false" :show-upload-list="false" :before-upload="handleBeforeUpload"
          class="avatar-uploader">
          <Image v-if="params.icon" :src="params.icon" alt="" :preview="false" />
          <div v-else>
            <UploadOutlined :style="{ fontSize: '26px' }" />
            <div class="ant-upload-text">上传</div>
          </div>
        </Upload>
      </FormItem>
    </Form>
  </Modal>
</template>
<script lang="ts" setup>
import {
  Card,
  Row,
  Col,
  List,
  Image,
  Button,
  Menu,
  MenuItem,
  Dropdown,
  Popconfirm,
  Modal,
  Form,
  FormItem,
  Input,
  TypographyParagraph,
  Tooltip,
  message,
  InputSearch,
  Upload,
  Select,
} from "ant-design-vue";
import { UploadOutlined } from "@ant-design/icons-vue";
import { onBeforeMount, ref } from "vue";
import { post, posturl, upload, geturl } from "../util/MyAxios";
import { Api } from "../util/Api";
import { showMessage } from "../util/Mes";
import type { SelectProps, UploadChangeParam } from "ant-design-vue";
const prefixCls = "list-card";
const rad = 1.1;
const radl = 1.2;
const params = ref({
  id: 0,
  urlpath: "",
  name: "",
  urlname: "",
  type: 0,
  num: 0,
  iconpath: "",
  icon: "",
});
const paramsType = ref({
  id: 0,
  name: "",
});
const opentype = ref<boolean>(false);
const open = ref<boolean>(false);
const linktypedata = ref<any>();
const linkdata = ref<any>();
const linkTypeTitle = ref("");
const linkTitle = ref("");
const optionsType = ref<SelectProps["options"]>([]);
const seltype = ref(0);
//页面初加载
onBeforeMount(() => {
  getLinkType();
  selLinks();
});

//获取链接类型信息
async function getLinkType() {
  await posturl(Api.LinkType_GetLinkType)
    .then((response) => {
      linktypedata.value = response.data;
      if (linktypedata.value && linktypedata.value.length > 0) {
        if (optionsType.value) {
          optionsType.value.splice(0, optionsType.value.length);
          for (let i = 0; i < linktypedata.value.length; i++) {
            optionsType.value.push({
              label: linktypedata.value[i].name,
              value: linktypedata.value[i].id,
            });
          }
        }
      }
    })
    .catch((error) => {
      console.error(error);
    });
}

//获取链接信息
async function selLinks() {
  params.value.name = "";
  params.value.type = seltype.value;
  await post(Api.Links_SelLinks, params.value)
    .then((response) => {
      if (response.data && response.data.length > 0) {
        for (let i = 0; i < response.data.length; i++) {
          response.data[i].icon = geturl() + "/IconImg/" + response.data[i].iconpath;
        }
      }
      linkdata.value = response.data;
    })
    .catch((error) => {
      console.error(error);
    });
}
//删除链接信息
async function delLinks(item) {
  await post(Api.Links_DelLinks, item)
    .then((response) => {
      showMessage(response.data, "删除链接");
      selLinks();
    })
    .catch((error) => {
      console.error(error);
    });
}
//删除链接类型信息
async function delLinkType(item) {
  await post(Api.LinkType_DelLinkType, item)
    .then((response) => {
      showMessage(response.data, "删除链接类型");
      getLinkType();
    })
    .catch((error) => {
      console.error(error);
    });
}
//添加一次链接类型热度
async function addLinkTypeClick(item) {
  await post(Api.LinkType_AddLinkTypeClick, item)
    .then((response) => {
      getLinkType();
    })
    .catch((error) => {
      console.error(error);
    });
}
//添加一次链接热度
async function addLinkClick(item) {
  await post(Api.Links_AddLinksClick, item)
    .then((response) => { })
    .catch((error) => {
      console.error(error);
    });
}

function selLinkByType(item) {
  addLinkTypeClick(item);
  seltype.value = item.id;
  selLinks();
}
function selOften() {
  seltype.value = 0;
  selLinks();
}
//添加链接类型
function btnAddLinkType() {
  paramsType.value.id = 0;
  paramsType.value.name = "";
  opentype.value = true;
  linkTypeTitle.value = "添加链接类型";
}
//打开添加链接页面
function btnAddLink() {
  params.value.id = 0;
  params.value.name = "";
  params.value.urlname = "";
  params.value.urlpath = "";
  params.value.num = 0;
  params.value.iconpath = "";
  params.value.icon = "";
  params.value.type =
    linktypedata.value.length > 0 ? linktypedata.value[0].id : 0;
  open.value = true;
  linkTitle.value = "添加链接";
}

function jumpWebUrl(item) {
  addLinkClick(item);
  window.open(item.urlpath, "_blank");
}

function clickLinkType(item) {
  paramsType.value.id = item.id;
  paramsType.value.name = item.name;
  linkTypeTitle.value = "修改链接类型";
  opentype.value = true;
}

function clickLink(item) {
  params.value.id = item.id;
  params.value.name = item.name;
  params.value.urlname = item.urlname;
  params.value.urlpath = item.urlpath;
  params.value.num = item.num;
  params.value.iconpath = item.iconpath;
  params.value.icon = item.icon;
  params.value.type = item.type;
  linkTitle.value = "修改链接";
  open.value = true;
}
//提交链接类型的操作
async function submitLinkType(b) {
  if (b) {
    if (paramsType.value && paramsType.value.id > 0) {
      await post(Api.LinkType_EditLinkType, paramsType.value)
        .then((response) => {
          showMessage(response.data, "修改链接类型");
        })
        .catch((error) => {
          console.error(error);
        });
    } else {
      await post(Api.LinkType_AddLinkType, paramsType.value)
        .then((response) => {
          showMessage(response.data, "添加链接类型");
        })
        .catch((error) => {
          console.error(error);
        });
    }
  }
  opentype.value = false;
  getLinkType();
}
//提交链接的操作
async function submitLink(b) {
  if (b) {
    if (params.value && params.value.id > 0) {
      await post(Api.Links_EditLinks, params.value)
        .then((response) => {
          showMessage(response.data, "修改链接");
        })
        .catch((error) => {
          console.error(error);
        });
    } else {
      await post(Api.Links_AddLinks, params.value)
        .then((response) => {
          showMessage(response.data, "添加链接");
        })
        .catch((error) => {
          console.error(error);
        });
    }
  }
  open.value = false;
  selLinks();
}
function getFaviconUrlFromUrl(webUrl) {
  try {
    const url = new URL(webUrl);
    const faviconUrl = `${url.protocol}//${url.hostname}/favicon.ico`;
    return faviconUrl;
  } catch (error) {
    console.error("Invalid URL:", webUrl);
    return null;
  }
}

function onSearch() {
  console.log("onSearch");
  if (params.value.urlpath && params.value.urlpath.concat(".")) {
    console.log("校验通过");
    let p = getFaviconUrlFromUrl(params.value.urlpath);
    console.log(p);
    message.info("获取失败" + p);
  }
}

const handleBeforeUpload = (file) => {
  const formData = new FormData();
  formData.append("file", file);
  return upload(Api.Links_UploadIconImg, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  })
    .then((response) => {
      params.value.icon = geturl() + "/IconImg/" + response.data;
      params.value.iconpath = response.data;
      return false;
    })
    .catch((error) => {
      console.error(error);
      return false;
    });
};
</script>
<style lang="less" scoped>
.list-card {
  &__link {
    margin-top: 10px;
    font-size: 14px;

    a {
      margin-right: 30px;
    }

    span {
      margin-left: 5px;
    }
  }

  &__card {
    width: 150px;
    margin-bottom: -8px;

    .ant-card-body {
      padding: 16px;
    }

    &-title {
      margin-bottom: 5px;
      color: #000;
      font-size: 16px;
      font-weight: 500;
      /* stylelint-disable-next-line order/properties-order */
      display: flex;
      align-items: center;

      .icon {
        margin-top: -5px;
        margin-right: 10px;
        font-size: 38px !important;
      }
    }

    &-detail {
      padding-top: 10px;
      padding-left: 10px;
      color: #000;
      font-size: 14px;
    }
  }
}

.parent-container {
  position: relative;
  /* 设置父容器的定位上下文 */
  width: 300px;
  /* 可以根据需要设置宽度和高度 */
  height: 200px;
  background-color: #f0f0f0;
  /* 仅为示例，显示父容器边界 */
}

.child-div {
  position: absolute;
  /* 绝对定位，相对于最近的定位祖先 */
  top: 0;
  /* 距离顶部的距离 */
  right: 5px;
  /* 距离右边的距离 */
  background-color: transparent;
  /* 背景颜色 */
  color: rgb(211 209 209);
  /* 文字颜色 */

  /* padding: 10px;  内边距 */
  font-size: 16px;
  /* 字体大小 */
}

.avatar-uploader>.ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  color: #999;
  font-size: 32px;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
